const config = require('../common/config');
const util = require('./util');

const storageKey = config.storage.keyAttendanceTime;

function hasAttendanceToday() {
    let lastAttendanceDate = wx.getStorageSync(storageKey),
        today = +new Date();

    return lastAttendanceDate && isSameDay(lastAttendanceDate, today);
}

function updateAttendanceDate() {
    let today = +new Date();
    return new Promise((resolve, reject) => {
        wx.setStorage({
            key: storageKey,
            data: today,
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err);
            }
        })
    })
}

/**
 * 判断两个日期是否为同一天
 * @param {number} date1
 * @param {number} date2
 */
function isSameDay(date1, date2) {
    return getFormattedDateYMD(date1) === getFormattedDateYMD(date2);
}

function getFormattedDateYMD(date) {
    let standard = new Date(date);
    return util.formatTime(standard).split(' ')[0];
}

module.exports = {
    hasAttendanceToday,
    updateAttendanceDate
};